<?php

require_once 'StarModule.php';

class StarGB extends StarModule
{
    public function init()
    {
        if (!$table = $this->fetchOne("SHOW TABLES LIKE '{$this->prefix}star_gb'")) {
            // instalace modulu - vytvoreni tabulky a naplneni default snippetu a chunku
            $sql = "CREATE TABLE `{$this->prefix}star_gb` (
                    `id`  bigint NOT NULL AUTO_INCREMENT ,
                    `date`  datetime NOT NULL ,
                    `author`  varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
                    `ip`  varchar(15) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
                    `email`  varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
                    `message`  text CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
                    `approved`  tinyint(1) NULL ,
                    `reply_to`  bigint NULL ,
                    `admin`  tinyint(1) NOT NULL DEFAULT 0 ,
                    PRIMARY KEY (`id`)
                    );";
            $this->query($sql);
            // chunks
            $dir = opendir(STARGB_PATH . 'chunks');
            while ($file=readdir($dir)) {
                if ($file[0]!='.') {
                    $chunk = file_get_contents(STARGB_PATH . 'chunks/' . $file);
                    $name = substr($file, 0, strlen($file)-4);
                    $sql = "INSERT INTO `{$this->prefix}site_htmlsnippets` (`name`, `snippet`)
                                                                     VALUES({$this->quote($name)}, {$this->quote($chunk)})";
                    $this->query($sql);
                }
            }
            // snippets
            $dir = opendir(STARGB_PATH . 'snippets');
            while ($file=readdir($dir)) {
                if ($file[0]!='.') {
                    $chunk = file_get_contents(STARGB_PATH . 'snippets/' . $file);
                    $name = substr($file, 0, strlen($file)-4);
                    $sql = "INSERT INTO `{$this->prefix}site_snippets` (`name`, `snippet`)
                                                                     VALUES({$this->quote($name)}, {$this->quote($chunk)})";
                    $this->query($sql);
                }
            }
        }
        if (!$table = $this->fetchOne("SHOW TABLES LIKE '{$this->prefix}star_gb_bans'")) {
            $sql = "CREATE TABLE `{$this->prefix}star_gb_bans` (
                    `ip`  varchar(15) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
                    `date`  datetime NOT NULL ,
                    PRIMARY KEY (`ip`)
                    );";
            $this->query($sql);
        }
        if (!$table = $this->fetchOne("SHOW TABLES LIKE '{$this->prefix}star_gb_config'")) {
            $sql = "CREATE TABLE `{$this->prefix}star_gb_config` (
                    `id`  varchar(15) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
                    `value`  text CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
                    PRIMARY KEY (`id`)
                    );";
            $this->query($sql);
            $sql = "INSERT INTO `{$this->prefix}star_gb_config` VALUES ('antispam', 'true');";
            $this->query($sql);
            $sql = "INSERT INTO `{$this->prefix}star_gb_config` VALUES ('autoapprove', 'false');";
            $this->query($sql);
            $sql = "INSERT INTO `{$this->prefix}star_gb_config` VALUES ('blocked_emails', '*.ru');";
            $this->query($sql);
            $sql = "INSERT INTO `{$this->prefix}star_gb_config` VALUES ('blocked_words', 'viagra,cialis,http,buy,-online,4u,adipex,advicer,baccarrat,blackjack,bllogspot,booker,byob,car-rental-e-site,car-rentals-e-site,carisoprodol,casino,casinos,chatroom,cialis,coolcoolhu,coolhu,credit-card-debt,credit-report-4u,cwas,cyclen,cyclobenzaprine,dating-e-site,day-trading,debt-consolidation,debt-consolidation-consultant,discreetordering,duty-free,dutyfree,equityloans,fioricet,flowers-leading-site,freenet-shopping,freenet,gambling-,hair-loss,health-insurancedeals-4u,homeequityloans,homefinance,holdem,holdempoker,holdemsoftware,holdemtexasturbowilson,hotel-dealse-site,hotele-site,hotelse-site,incest,insurance-quotesdeals-4u,insurancedeals-4u,jrcreations,levitra,macinstruct,mortgage-4-u,mortgagequotes,online-gambling,onlinegambling-4u,ottawavalleyag,ownsthis,palm-texas-holdem-game,paxil,penis,pharmacy,phentermine,poker-chip,poze,pussy,rental-car-e-site,ringtones,roulette ,shemale,shoes,slot-machine,texas-holdem,thorcarlson,top-site,top-e-site,tramadol,trim-spa,ultram,valeofglamorganconservatives,viagra,vioxx,xanax,zolus,v1agra,vi4gra,v14gr4,viagr4');";
            $this->query($sql);
            $sql = "INSERT INTO `{$this->prefix}star_gb_config` VALUES ('language', 'english');";
            $this->query($sql);
            $sql = "INSERT INTO `{$this->prefix}star_gb_config` VALUES ('delete_days', '30');";
            $this->query($sql);
        }
        // auto delete after 1 month
        $days = intval($this->getConfig('delete_days'));
        if ($days<=0) {
            $days = 30;
            $sql = "REPLACE INTO `{$this->prefix}star_gb_config` VALUES ('delete_days', '30');";
            $this->query($sql);
        }
        $sql = "DELETE FROM `{$this->prefix}star_gb` WHERE date < CURRENT_TIMESTAMP - INTERVAL {$days} DAY AND approved = 0";
        $this->query($sql); 
    }

    public function indexAction()
    {
        if (!empty($_GET['approved'])) {
            $id = intval($_GET['approved']);
            $sql = "UPDATE `{$this->prefix}star_gb` SET `approved` = 1 WHERE id = $id LIMIT 1";
            $this->query($sql);
        }
        if (!empty($_GET['spam'])) {
            $id = intval($_GET['spam']);
            $sql = "UPDATE `{$this->prefix}star_gb` SET `approved` = 0 WHERE id = $id LIMIT 1";
            $this->query($sql);
        }
        if (!empty($_GET['delete'])) {
            $id = intval($_GET['delete']);
            $sql = "DELETE FROM `{$this->prefix}star_gb` WHERE id = $id LIMIT 1";
            $this->query($sql);
        }
        if (!empty($_GET['ban'])) {
            $ip = preg_replace("/[^0-9.]/", '', $_GET['ban']);
            $sql = "REPLACE INTO `{$this->prefix}star_gb_bans` (`ip`, `date`) VALUES ('$ip', CURRENT_TIMESTAMP)";
            $this->query($sql);
            $sql = "UPDATE `{$this->prefix}star_gb` SET `approved` = 0 WHERE ip = '$ip'";
            $this->query($sql);
        }
        if (!empty($_GET['trash'])) {
            $sql = "DELETE FROM `{$this->prefix}star_gb` WHERE `approved` = 0";
            $this->query($sql);
        }
        if (!empty($_POST['unban'])) {
            $ip = preg_replace("/[^0-9.]/", '', $_POST['unban']);
            $sql = "DELETE FROM `{$this->prefix}star_gb_bans` WHERE `ip` = '{$ip}'";
            $this->query($sql);
        }
        if (!empty($_POST['var'])) {
            if (is_array($_POST['var'])) {
                foreach ($_POST['var'] as $key => $value) {
                    $sql = "REPLACE INTO `{$this->prefix}star_gb_config` (`id`, `value`) VALUES ({$this->quote($key)}, {$this->quote($value)})";
                    $this->query($sql);
                }
            }
        }
    
        $langs = array();
        $dir = opendir(STARGB_PATH . 'lng');
        while ($file=readdir($dir)) {
            if ($file[0]!='.') {
                $langs[] = substr($file, 0, strlen($file) - 4);
            }
        }
        $this->view->languages = $langs;
    
        $this->view->waiting = $this->fetchAll("SELECT * FROM `{$this->prefix}star_gb` WHERE approved IS NULL");
        $this->view->approved = $this->fetchAll("SELECT * FROM `{$this->prefix}star_gb` WHERE approved = 1");
        $this->view->spam = $this->fetchAll("SELECT * FROM `{$this->prefix}star_gb` WHERE approved = 0");
        $this->view->bans = $this->fetchAll("SELECT * FROM `{$this->prefix}star_gb_bans` ORDER BY ip");
        $this->view->var = $this->getConfig();
    }

    public function getConfig($id = false)
    {
        if ($id==false) {
            $sql = "SELECT * FROM `{$this->prefix}star_gb_config`";
            $vars = array();
            foreach ($this->fetchAll($sql) as $row) {
                $vars[$row['id']] = $row['value'];
            }
            return $vars;
        } else {
            $sql = "SELECT value FROM `{$this->prefix}star_gb_config` WHERE id = {$this->quote($id)}";
            return $this->fetchOne($sql);
        }
    }
    
    public function addMessage($author, $email, $message, $reply)
    {
        $ip = $_SERVER['REMOTE_ADDR'];
        $approved = 'NULL';
        if ($this->getConfig('autoapprove')=='true') {
            $approved = '1';
        }
        if ($this->getConfig('antispam')=='true') {
            $l = $this->getSpamLevel($message, $email);
            if ($l<=0) {
                $approved = '1';
            }
            if ($l>=3) {
                $approved = '0';
            }
        }
        
        $sql = "INSERT INTO `{$this->prefix}star_gb` (`date`, `author`, `email`, `ip`, `message`, `approved`)
                                            VALUES (CURRENT_TIMESTAMP, {$this->quote($author)}, {$this->quote($email)}, {$this->quote($ip)}, {$this->quote($message)}, {$approved})";
        $this->query($sql);
    }
    
    public function settingsAction()
    {
        
    }
    
    public function getSpamLevel(&$text, $email)
    {
        $l = 0; // initial level is zero
        // check for bad words
        $words = explode(',', $this->getConfig('blocked_words'));
        foreach ($words as $word) {
            $word = trim($word);
            if ($word!='') {
                if (preg_match("/".preg_quote($word, '/')."/", $text)) {
                    $l++;
                }
            }
        }
        // cheack for bad mails
        $email = trim($email);
        if (!preg_match("/^[a-zA-Z0-9_+.-]+[@][a-zA-Z0-9_+.-]+\.[a-zA-Z]+$/", $email)) {
            $l++;
        } else {
            $emails = explode(',', $this->getConfig('blocked_emails'));
            foreach ($emails as $mail) {
                $mail = trim($mail);
                if ($mail!='') {
                    $ex = '';
                    if (count(explode('*', $mail))>1) {
                        foreach (explode('*', $mail) as $key => $part) {
                            if ($key!=0) {
                                $ex .= ".*";
                            }
                            $ex .= preg_quote($part, '/');
                        }
                    } else {
                        $ex = preg_quote($mail, '');
                    }
                    if (preg_match("/^{$ex}$/", $email)) {
                        $l++;
                    }
                }
            }
        }
        // check for JS test
        if (substr($text, -8)==date('dYm')) {
            $l--;
            $text = substr($text, 0, strlen($text) - 9);
        }
        // ip
        if ($this->isBanned($_SERVER['REMOTE_ADDR'])) {
            $l += 10;
        }
        
        return $l;
    }
    
    public function isBanned($ip)
    {
        $sql = "SELECT ip FROM `{$this->prefix}star_gb_bans` WHERE ip = {$this->quote($ip)}";
        return ($ban = $this->fetchOne($sql));
    }
}
